#include <stdlib.h>
#include "mk_node_list.h"

mk_node_list::mk_node_list()
{
	m_pHead = NULL;
}

mk_node_list::~mk_node_list()
{
	remove_all();
}

void mk_node_list::remove_all()
{
	while (m_pHead != NULL)
	{
		mk_node *node = m_pHead;
		m_pHead = m_pHead->get_next_node();
		delete node;
	}
}


int mk_node_list::add(void * pData)
{
	mk_node * pNode = new mk_node();
	pNode->set_data(pData);

	if (m_pHead == NULL)
	{
		m_pHead = pNode;
		return 1;
	}
	else
	{
		mk_node * pTail = get_tail();
		if(pTail == NULL)
			m_pHead = pNode;
		else
			pTail->set_next_node(pNode);
	}

	return get_count();
}

int mk_node_list::remove( void * pData )
{
	mk_node * pNode = m_pHead;

	if(pNode->get_data() == pData)
	{
		m_pHead = pNode->get_next_node();
		delete pNode;
		return 0;
	}

	mk_node * pPrev = pNode;
	pNode = pNode->get_next_node();

	while (pNode != NULL)
	{
		if(pNode->get_data() != pData)
		{
			pPrev = pNode;
			pNode = pNode->get_next_node();
		}
		else
		{
			pPrev->set_next_node(pNode->get_next_node());
			delete pNode;
			return 0;
		}
	}

	return 1; //not found
}


int mk_node_list::get_count()
{
	long nCount = 0;

	mk_node * pNode = m_pHead;
	while (pNode != NULL)
	{
		nCount ++;
		pNode = pNode->get_next_node();
	}

	return nCount;
}

mk_node * mk_node_list::get_head()
{
	return m_pHead;
}

mk_node *  mk_node_list::get_tail()
{
	mk_node * pNode = m_pHead;
	while (pNode != NULL)
	{
		if( pNode->get_next_node() == NULL)
		{
			return pNode;
		}

		pNode = pNode->get_next_node();
	}

	return NULL;
}


